<template>
  <div class="user-page">
    <!-- 固定在顶部的用户信息区域 -->
    <div class="user-info fixed-header">
      <div class="avatar-section">
        <img :src="user.avatar" alt="用户头像" class="avatar" @click="handleUserAvatarClick">
        <input
            type="file"
            ref="fileInput"
            @change="handleAvatarUpload"
            accept="image/*"
            style="display: none;"
        />
        <span class="login-text" v-if="!user.isLoggedIn" @click="handleUserNameClick">点击登录</span>
        <span class="username" v-else>{{ user.username }}</span>
      </div>
      <!-- 退出登录按钮 -->
      <button class="logout-btn" v-if="user.isLoggedIn" @click="handleLogout">
        退出登录
      </button>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 订单和功能区域 -->
      <div class="order-section">
        <h3 class="section-title">我的订单</h3>
        <div class="order-types">
          <div class="order-type" @click="handleMovieOrderClick">
            <div class="order-icon-wrapper">
              <svg class="order-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
                <path
                    d="M844.832 885.344c-30.485333-20.714667-77.781333-18.965333-144.053333 9.386667A425.024 425.024 0 0 1 512 938.666667C276.362667 938.666667 85.333333 747.637333 85.333333 512S276.362667 85.333333 512 85.333333s426.666667 191.029333 426.666667 426.666667a425.013333 425.013333 0 0 1-44.405334 189.717333 32 32 0 0 1-57.301333-28.490666A361.013333 361.013333 0 0 0 874.666667 512c0-200.298667-162.368-362.666667-362.666667-362.666667S149.333333 311.701333 149.333333 512s162.368 362.666667 362.666667 362.666667c56.704 0 111.488-13.013333 161.12-37.653334l1.6-0.746666c84.746667-36.437333 154.176-39.125333 206.08-3.861334a32 32 0 1 1-35.968 52.938667zM512 416a64 64 0 1 1 0-128 64 64 0 0 1 0 128z m160 160a64 64 0 1 1 0-128 64 64 0 0 1 0 128zM512 736a64 64 0 1 1 0-128 64 64 0 0 1 0 128zM352 576a64 64 0 1 1 0-128 64 64 0 0 1 0 128z"
                    fill="#ff4e64"></path>
              </svg>
            </div>
            <span class="order-text">电影票</span>
          </div>
          <div class="order-type" @click="handlePerformanceOrderClick">
            <div class="order-icon-wrapper">
              <svg t="1754452482799" class="order-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
                <path
                    d="M608 383.989333c38.858667 29.194667 64 75.669333 64 128.010667 0 88.362667-71.637333 160-160 160-88.362667 0-160-71.637333-160-160 0-88.362667 71.637333-160 160-160 36.021333 0 69.258667 11.904 96 31.989333V181.333333a32 32 0 0 1 64 0v330.666667a32 32 0 0 1-64 0V383.989333zM512 85.333333a32 32 0 0 1 0 64c-200.298667 0-362.666667 162.368-362.666667 362.666667s162.368 362.666667 362.666667 362.666667 362.666667-162.368 362.666667-362.666667a360.938667 360.938667 0 0 0-40.448-166.613333 32 32 0 1 1 56.821333-29.44A424.938667 424.938667 0 0 1 938.666667 512c0 235.637333-191.029333 426.666667-426.666667 426.666667S85.333333 747.637333 85.333333 512 276.362667 85.333333 512 85.333333z m0 522.666667a96 96 0 1 0 0-192 96 96 0 0 0 0 192z m213.333333-330.666667c-61.802667 0-117.333333-43.157333-117.333333-96s55.530667-96 117.333333-96c63.125333 0 117.333333 40.650667 117.333334 96s-54.208 96-117.333334 96z m0-64c31.125333 0 53.333333-16.650667 53.333334-32s-22.208-32-53.333334-32c-29.482667 0-53.333333 18.538667-53.333333 32s23.850667 32 53.333333 32z"
                    fill="#ff4e64"></path>
              </svg>
            </div>
            <span class="order-text">演出票</span>
          </div>
        </div>
      </div>

      <!-- 个人信息配置区域 -->
      <div class="profile-section">
        <h3 class="section-title">个人信息</h3>
        <form @submit.prevent="handleSaveProfile" class="profile-form">
          <div class="form-group">
            <label for="username">用户名</label>
            <input
                type="text"
                id="username"
                v-model="profileForm.username"
                :disabled="!isEditing"
                required
            />
          </div>
          <div class="form-group">
            <label>性别</label>
            <div class="radio-group">
              <label class="radio-label">
                <input
                    type="radio"
                    v-model="profileForm.gender"
                    value="1"
                    :disabled="!isEditing"
                />
                <span class="radio-custom"></span>
                <span class="radio-text">男</span>
              </label>
              <label class="radio-label">
                <input
                    type="radio"
                    v-model="profileForm.gender"
                    value="2"
                    :disabled="!isEditing"
                />
                <span class="radio-custom"></span>
                <span class="radio-text">女</span>
              </label>
            </div>
          </div>
          <div class="form-group">
            <label for="birthday">生日</label>
            <input
                type="date"
                id="birthday"
                v-model="profileForm.birthday"
                :disabled="!isEditing"
            />
          </div>
          <div class="form-actions" v-if="user.isLoggedIn">
            <button
                type="button"
                class="edit-btn"
                @click="toggleEditMode"
            >
              {{ isEditing ? '取消' : '修改' }}
            </button>
            <button
                type="submit"
                class="save-btn"
                :disabled="!isEditing"
            >
              保存
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <Navigation />

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay">
      <div class="modal-content">
        <h3>确认修改</h3>
        <p>确定要保存修改的个人信息吗？</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="cancelSave">取消</button>
          <button class="confirm-btn" @click="confirmSave">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance, onMounted, reactive, ref} from 'vue';
import { useRouter } from 'vue-router';
import defaultAvatar from '@/assets/default-avatar.png';
import Navigation from "@/components/homepageComponents/Navigation.vue";

const global = getCurrentInstance().appContext.config.globalProperties;
const router = useRouter();

// 用户数据
const user = reactive({
  avatar: defaultAvatar,
  username: '未登录用户',
  gender: '',
  birthday: '',
  isLoggedIn: false
});

// 表单数据
const profileForm = reactive({
  username: '',
  gender: '',
  birthday: ''
});

// 编辑状态
const isEditing = ref(false);
const showConfirmModal = ref(false);
const fileInput = ref(null);

// 备份原始数据
let originalProfileData = {};

// 切换编辑模式
const toggleEditMode = () => {
  if (isEditing.value) {
    // 取消编辑，恢复数据
    Object.assign(profileForm, originalProfileData);
    isEditing.value = false;
  } else {
    // 开始编辑，备份当前数据
    originalProfileData = {...profileForm};
    isEditing.value = true;
  }
};

// 处理保存
const handleSaveProfile = () => {
  showConfirmModal.value = true;
};

// 取消保存
const cancelSave = () => {
  showConfirmModal.value = false;
};

// 确认保存
const confirmSave = async () => {
  showConfirmModal.value = false;

  console.log(profileForm);
  user.username = profileForm.username;
  user.gender = profileForm.gender;
  user.birthday = profileForm.birthday;

  try {
    const resp = await global.$http.post('/User/UpdateUserInfo', {
      id: localStorage.getItem('userId'),
      username: user.username,
      gender: user.gender,
      birthday: user.birthday
    });

    console.log(resp.data);

    // 更新用户数据
    Object.assign(user, profileForm);
    isEditing.value = false;
  } catch (error) {
    console.error('保存个人信息失败:', error);
    alert('保存失败，请重试');
  }
};

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('Authorization');
  localStorage.removeItem('userId');
  user.isLoggedIn = false;
  user.username = '登录未用户';
  user.gender = '';
  user.birthday = '';
  user.avatar = '';
  router.push({ name: 'LoginView' });
};

// 其他方法保持不变...
const handleUserNameClick = () => {
  if (!user.isLoggedIn) {
    router.push({ name: 'LoginView' });
  }
};

const handleUserAvatarClick = () => {
  if (!user.isLoggedIn) {
    router.push({ name: 'LoginView' });
  } else {
    fileInput.value.click();
  }
};

const handleMovieOrderClick = () => {
  if (!user.isLoggedIn) {
    router.push({ name: 'LoginView' });
  } else {
    router.push({ name: 'orderView' });
    return;
  }
};

const handlePerformanceOrderClick = () => {
  if (!user.isLoggedIn) {
    router.push({ name: 'LoginView' });
  } else {
    let userId = localStorage.getItem('userId');
    router.push({ name: 'performance-order', query: { userId: userId }});
  }
};

const handleAvatarUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    return;
  }

  try {
    // 1. 获取当前用户ID（根据您的系统获取方式）
    let userId = localStorage.getItem('userId');

    // 2. 构建FormData
    const formData = new FormData();
    formData.append('image', file);
    formData.append('userId', userId);

    const response = await global.$http.post('/User/UploadAvatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    });

    console.log(response);

    if (response.data === '头像更新成功'){
      const resp = await global.$http.get('/User/GetUserInfo', {
        params: {
          userId: userId
        }
      });

      user.avatar = resp.data.avatar;

    } else {
      console.log('头像更新失败');
    }

  } catch (error) {
    console.error('上传失败:', error);
    if (error.response?.status === 401) {
      alert('登录已过期，请重新登录');
      router.push('/LoginView');
    } else if (error.response?.data?.includes('bucket acl')) {
      alert('存储权限不足，请联系管理员'); // 针对您截图中的OSS权限错误
    } else {
      alert('上传失败: ' + (error.response?.data || '请重试'));
    }
  }
};

onMounted(async () => {
  // 检查本地存储中的登录状态
  const userId = localStorage.getItem('userId');

  console.log(userId);
  console.log(localStorage.getItem('Authorization'));
  if (userId) {
    user.isLoggedIn = true;

    try {
      // 这里应该调用API获取用户信息
      const resp = await global.$http.get('/User/GetUserInfo', {
        params: {
          userId: userId
        }
      });

      console.log(resp.data);

      // 更新用户数据
      Object.assign(user, {
        username: resp.data.username,
        gender: resp.data.gender,
        birthday: resp.data.birthday,
        avatar: resp.data?.avatar || defaultAvatar
      });

      // 初始化表单数据
      Object.assign(profileForm, {
        username: resp.data.username,
        gender: resp.data.gender,
        birthday: resp.data.birthday
      });
    } catch (err) {
      console.error('获取用户信息失败:', err);
    }
  }
});
</script>

<style scoped>
.user-page {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  max-width: 500px;
  margin: 0 auto;
  background-color: #f8f8f8;
  min-height: 100vh;
  color: #333;
  position: relative;
}

/* 固定在顶部的用户信息 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  max-width: 500px;
  margin: 0 auto;
  background: #ff4e64;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 15px;
  color: white;
}

.avatar-section {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
  margin-right: 15px;
  object-fit: cover;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.login-text, .username {
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 退出登录按钮样式 */
.logout-btn {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

/* 主要内容区域 */
.main-content {
  padding: 90px 15px 80px;
  min-height: calc(100vh - 170px);
}

/* 订单区域 */
.order-section {
  margin-top: 15px;
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.order-types {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
}

.order-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
  transition: all 0.3s ease;
  width: 45%;
}

.order-type:hover {
  background-color: #fff5f7;
}

.order-icon-wrapper {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;

  border-radius: 50%;
  margin-bottom: 10px;
}

.order-icon {
  width: 40px;
  height: 40px;
}

.order-text {
  font-size: 15px;
  color: #666;
  font-weight: 500;
}

/* 个人信息区域 */
.profile-section {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 15px;
}

.form-group input[type="text"],
.form-group input[type="date"] {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-sizing: border-box;
  font-size: 15px;
  transition: border-color 0.3s;
}

.form-group input[type="text"]:focus,
.form-group input[type="date"]:focus {
  border-color: #ff758c;
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 117, 140, 0.2);
}

.form-group input:disabled {
  background-color: #f9f9f9;
  color: #666;
  cursor: not-allowed;
}

.radio-group {
  display: flex;
  gap: 20px;
  margin-top: 8px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
}

.radio-label input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.radio-custom {
  position: relative;
  display: inline-block;
  width: 18px;
  height: 18px;
  border: 2px solid #ccc;
  border-radius: 50%;
  margin-right: 8px;
  transition: all 0.3s;
}

.radio-label input:checked ~ .radio-custom {
  border-color: #ff758c;
  background-color: #ff758c;
}

.radio-label input:checked ~ .radio-custom::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.radio-text {
  font-size: 15px;
  color: #333;
}

/* 按钮样式 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 25px;
  padding-bottom: 10px;
}

.edit-btn {
  padding: 10px 20px;
  border: 1px solid #ff758c;
  border-radius: 8px;
  background-color: white;
  color: #ff758c;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 15px;
}

.edit-btn:hover {
  background-color: #fff5f7;
}

.save-btn {
  padding: 10px 25px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #ff758c, #ff7eb3);
  color: white;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(255, 117, 140, 0.3);
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 117, 140, 0.3);
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

/* 确认弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 25px;
  border-radius: 12px;
  width: 85%;
  max-width: 320px;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
  font-size: 18px;
  margin-bottom: 15px;
}

.modal-content p {
  color: #666;
  font-size: 15px;
  margin-bottom: 20px;
}

.modal-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.modal-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.3s;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #666;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-btn {
  background: linear-gradient(135deg, #ff758c, #ff7eb3);
  color: white;
  box-shadow: 0 2px 5px rgba(255, 117, 140, 0.3);
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 117, 140, 0.3);
}
</style>